<template>
  <div class="container">
    <el-alert
      :title="appInfo.authContent"
      type="error"
      show-icon
      :closable="false"
      style="margin-bottom: 20px"
      v-if="handlerType === 'read' && appInfo.authContent"
    />
    <div class="tit-wrap flex-xbt">
      <h2>{{ appId ? '编辑' : '创建' }}流程子流程</h2>
    </div>
    <div class="form-wrap input-bgc">
      <form-comp
        ref="form"
        size="large"
        labelWidth="100"
        btn-align="right"
        v-model:formData="formData"
        :form-item="formItem"
        :disabled="disabledData"
        :button="button"
      >
        <template v-slot:uploadImg>
          <upload
            iconWidth="188"
            iconHeight="116"
            :uploadUrl="`${baseURL}/bioinfor/auth/upload/uploadImage`"
            :oldFileUrl="formData.image"
            @uploadRespLoaded="uploadImgResp"
          ></upload>
          <p>支持jpg/png格式图片，文件需小于2MB</p>
        </template>
        <template v-slot:uploadVideo>
          <upload-video
            iconWidth="188"
            iconHeight="116"
            :uploadUrl="`${baseURL}/bioinfor/auth/upload/uploadVideo`"
            :oldFileUrl="formData.video"
            @uploadRespLoaded="uploadVideoResp"
          ></upload-video>
        </template>
        <template v-slot:useSlot="{ column }">
          <template v-if="column.prop == 'subType'">
            <el-cascader
              :disabled="handlerType === 'read'"
              v-model="formData.applicationType"
              :options="column.options"
              :props="{ label: 'value', value: 'key', children: 'sub' }"
              @change="(value) => onTypeChange(value, 'applicationType')"
            />
          </template>
          <template v-if="column.prop == 'useLanguage'">
            <ul style="width: 200px" class="flex-yc">
              <li class="flex-yc" v-for="(item, i) in column.options" :key="i">
                <div style="padding: 0 10px">{{ item.lan }}</div>
                <el-select
                  placeholder="版本"
                  size="large"
                  multiple
                  :disabled="handlerType === 'read'"
                  v-model="languageVersion[item.lan]"
                  style="width: 100px"
                  @change="onLanguageChange"
                >
                  <el-option
                    v-for="option in item.version"
                    :key="option"
                    :label="option"
                    :value="option"
                  />
                </el-select>
              </li>
            </ul>
          </template>
        </template>
      </form-comp>
    </div>
  </div>
</template>

<script setup lang="ts">
import upload from '@/components/control/upload/index.vue'
import uploadVideo from '@/components/control/uploadVideo/index.vue'
import formComp from '@/components/form/form.vue'
import { onBeforeMount, onMounted, reactive, ref } from 'vue'
import { FormButtonType, FormItemType } from '@/components/form/type'
import {
  reqCreateApp,
  reqGetAppInfo,
  reqGetConfigContent,
  reqGetConfigKeys,
} from '../../api/flowapp'
import {
  reqCreateFlowApp,
  reqUpdateFlowApp,
  baseURL,
} from '../../api/flowapp'
import { MsgError, MsgSuccess } from '@/utils/utils'
import { useRoute, useRouter } from 'vue-router'
import { useApplicationHook } from '@/pages/member/views/flowapp/composables/subapplication.ts'
import {
  languageVersion as languageVersionType,
  respAppDetailData,
} from '@/pages/member/api/types/application'
const router = useRouter()
const route = useRoute()
const appId = Number(route.query.appId)
const handlerType = route.query.handlerType || ''
// 智能流程ID
const flowId = route.query.flowId as string

const languageVersion = ref<Record<string, string>>({})
const disabledData = ref({})
const { formData, formItem } = useApplicationHook()

onBeforeMount(() => getCommonConfigKeys())
onMounted(async () => {
  if (appId) await getAppData(appId)
  if (handlerType === 'read') {
    for (let key in formData.value) disabledData.value[key] = true
  }
})

const getCommonConfigKeys = async () => {
  const { data } = await reqGetConfigKeys()
  const formItemNew: FormItemType[] = []
  for (let i = 0; i < data.length; i++) {
    const { data: options } = await reqGetConfigContent(data[i].key)
    formItemNew.push({
      type: 'slot',
      slotName: 'useSlot',
      label: data[i].value,
      prop: data[i].key === 'applicationLan' ? 'useLanguage' : 'subType',
      required: true,
      options,
    })
  }
  formItem.splice(-2, 0, ...formItemNew)
}

const appInfo = ref<respAppDetailData>({})
const getAppData = async (id: number) => {
  let resp = await reqGetAppInfo(id)
  appInfo.value = resp.data
  localStorage.setItem('appInfo', JSON.stringify(resp.data))
  if (resp.code === 0) {
    formData.value = resp.data
    formData.value.applicationType = [resp.data.type, resp.data.subType]
    resp.data.useLanguage.map((item) => {
      languageVersion.value = {
        ...languageVersion.value,
        ...{
          [item.lan]: item.version,
        },
      }
    })
  }
  console.log(formData.value, 222)
}

const button = reactive<FormButtonType[]>([
  {
    key: 'cancel',
    label: '返回',
    callback: () => router.back(),
  },
  {
    key: 'submit',
    type: 'primary',
    label: '确定',
    callback: () => onCreateApplication(),
  },
])

const onTypeChange = (value, type) => {
  formData.value.type = value[0]
  formData.value.subType = value[1]
  formData.value[type] = value
}

const onLanguageChange = () => {
  let languageAry: languageVersionType[] = []
  for (const resolveKey in languageVersion.value) {
    if (languageVersion.value[resolveKey]?.length > 0) {
      languageAry.push({
        lan: resolveKey,
        version: [...languageVersion.value[resolveKey]],
      })
    }
  }
  formData.value.useLanguage = languageAry
}

const onCreateApplication = async () => {
  console.log(formData.value)
  if (handlerType === 'read') {
    //router.push('/application/cloud?appId=' + appId)
    router.push('/flowapp/subindex?flowId=' + flowId)
    return false
  }

  if (appId) formData.value.id = appId
  let saveData = JSON.parse(JSON.stringify(formData.value))
  saveData.flowId = flowId
  // delete saveData.applicationType
  let resp = null
  if (appId) {
    saveData.applicationId = appId
    resp = await reqUpdateFlowApp(saveData)
  } else {
    resp = await reqCreateFlowApp(saveData)
  }

  const msg = appId ? '编辑' : '创建'
  if (resp.code !== 0) MsgError(resp.msg || msg + '失败')
  else {
    MsgSuccess(resp.msg || msg + '成功')
    const id = appId || resp.data
    router.push('/flowapp/subindex?flowId=' + flowId)
    //router.push('/application/cloud?appId=' + id)
  }
}

const uploadImgResp = async (resp: string) => {
  if (resp.data === '') return MsgError(resp.msg)
  else {
    formData.value.image = resp.data.data
  }
}
const uploadVideoResp = async (resp: string) => {
  if (resp.data === '') return MsgError(resp.msg)
  else {
    formData.value.video = resp.data.data
  }
}
</script>

<style scoped lang="scss">
.container {
  padding: 30px 27px;
  background-color: #fff;
  border-radius: 4px;

  .tit-wrap {
    margin-bottom: 45px;

    h2 {
      font-size: 20px;
      color: #021429;
    }
  }

  .form-wrap {
    width: 870px;

    p {
      margin-top: 100px;
      margin-left: 8px;
      font-size: 13px;
      line-height: 1;
      color: #425779;
    }
  }
}
</style>
